#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Login Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /boot/dietpi/dietpi-login
	# - Called in interactive bash shells from: /etc/bashrc.d/dietpi.bash
	#////////////////////////////////////

	#/////////////////////////////////////////////////////////////////////////////////////
	# Globals
	#/////////////////////////////////////////////////////////////////////////////////////
	readonly FP_DIETPI_FIRSTRUNSETUP_LOG='/var/tmp/dietpi/logs/dietpi-firstrun-setup.log'
	readonly FP_DIETPI_FIRSTRUNSETUP_PID='/tmp/.dietpi-login_firstrun_setup.pid' # Must be on RAM, in case of reboot from dietpi-software etc, to reset file before this script can remove it.
	readonly FP_DIETPI_FIRSTRUNSETUP_ERR='/tmp/.dietpi-login_firstrun_setup_err' # Error flag to allow a second instance kill and repeat firstrun setup

	Show_License(){

		[[ -f '/var/lib/dietpi/license.txt' ]] || return
		G_WHIP_VIEWFILE /var/lib/dietpi/license.txt
		rm /var/lib/dietpi/license.txt

	}

	# AutoStart after autologin
	# - $1: AutoStart index
	Run_AutoStart(){

		local auto_start_index=$1

		# Kodi
		if (( $auto_start_index == 1 )); then

			exec /boot/dietpi/misc/start_kodi

		# Desktop autologin (for root user only, as non-root user autologins are done via LightDM service since v7.2)
		elif (( $auto_start_index == 2 )); then

			unset -v G_DIETPI_LOGIN
			exec startx

		# OpenTyrian
		elif (( $auto_start_index == 4 )); then

			exec /usr/games/opentyrian/run

		# DietPi-CloudShell
		elif (( $auto_start_index == 5 )); then

			exec /boot/dietpi/dietpi-cloudshell 1

		# Amiberry standard boot
		elif (( $auto_start_index == 8 )); then

			systemctl start amiberry

		# DXX-Rebirth
		elif (( $auto_start_index == 9 )); then

			exec /mnt/dietpi_userdata/dxx-rebirth/run.sh

		# CAVA
		elif (( $auto_start_index == 10 )); then

			# Disable screen blanking
			setterm --blank 0 --powersave off

			# Wait for MPD FIFO
			local count=1 timeout=10
			until [[ -e '/tmp/mpd.fifo' ]]
			do
				(( $count > $timeout )) && { G_DIETPI-NOTIFY 1 'Waiting for MPD FIFO timed out. Aborting...'; return 1; }
				G_DIETPI-NOTIFY 2 "Waiting for MPD FIFO before starting CAVA ($count/$timeout)"
				sleep 1
				((count++))
			done

			# Start CAVA
			exec cava

		# Chromium
		elif (( $auto_start_index == 11 )); then

			exec /var/lib/dietpi/dietpi-software/installed/chromium-autostart.sh

		fi

	}

	# Force interactive prompt on unexpected state or failure, to allow user choice to retry or exit
	Prompt_on_Failure(){

		/boot/dietpi/func/dietpi-banner 0

		# Force interactive mode to show G_WHIP error prompts
		# - NB: We need to write this to dietpi.txt as well to not have it overwritten on next loop.
		export G_INTERACTIVE=1
		G_CONFIG_INJECT 'AUTO_SETUP_AUTOMATED=' 'AUTO_SETUP_AUTOMATED=0' /boot/dietpi.txt

		local pid_loginerror=$$
		[[ -f $FP_DIETPI_FIRSTRUNSETUP_ERR ]] && pid_loginerror=$(<$FP_DIETPI_FIRSTRUNSETUP_ERR)
		if [[ $pid_loginerror != "$$" ]]; then

			G_WHIP_BUTTON_OK_TEXT='Take over' G_WHIP_BUTTON_CANCEL_TEXT='Retry'
			G_WHIP_DEFAULT_ITEM='yes' G_WHIP_YESNO "[FAILED] Unknown install state/First run setup failed on another screen (PID=$pid_loginerror).
\nYou can <Take over> the error handling on this screen and kill the other DietPi-Login session.
\nElse you can finish the error handling on the other DietPi-Login session and <Retry> the login script on this session afterwards." || return
			kill -9 "$pid_loginerror"

		fi

		echo $$ > $FP_DIETPI_FIRSTRUNSETUP_ERR
		if G_WHIP_DEFAULT_ITEM='yes' G_WHIP_YESNO "[FAILED] Unknown install state/First run setup failed\n
An error has occured either during first run update or installs.\n
First run setup will now attempt to re-apply the last step, forced as interactive run.
If this repeatedly fails, please collect all terminal output and the content of $FP_DIETPI_FIRSTRUNSETUP_LOG if available and report this issue to: https://github.com/MichaIng/DietPi/issues\n
Would you like to restart the first run setup and installation?"; then

			# Reset and force re-run of first run setup
			rm $FP_DIETPI_FIRSTRUNSETUP_ERR
			killall -qw dietpi-software dietpi-update
			echo 0 > /boot/dietpi/.install_stage

		else

			rm $FP_DIETPI_FIRSTRUNSETUP_ERR
			exit 1

		fi

	}

	# First Run Setup
	Run_DietPi_First_Run_Setup(){

		# Set non-interactive if automated firstrun setup has been chosen
		grep -q '^[[:blank:]]*AUTO_SETUP_AUTOMATED=1' /boot/dietpi.txt && export G_INTERACTIVE=0

		# Prompt and wait if this script runs in other session already
		local pid_firstrunsetup=$$
		[[ -f $FP_DIETPI_FIRSTRUNSETUP_PID ]] && pid_firstrunsetup=$(<$FP_DIETPI_FIRSTRUNSETUP_PID)

		# Unknown install state/First run setup failed in other session, forcing interactive whiptail prompt. Allow to take over and repeat on this session.
		if [[ -f $FP_DIETPI_FIRSTRUNSETUP_ERR ]]; then

			Prompt_on_Failure

		elif [[ $pid_firstrunsetup != "$$" ]]; then

			local additional_text='Please resume setup on the active screen.'
			[[ $G_INTERACTIVE == 0 ]] && additional_text='Automated setup is in progress. When completed, the system will be rebooted.'

			G_WHIP_MSG "[ INFO ] DietPi first run setup is currently running on another screen (PID=$pid_firstrunsetup).\n\n$additional_text"

			local restart_loop_delay=5
			G_DIETPI-NOTIFY 2 "Waiting $restart_loop_delay seconds before checking again. Please wait... (Press CTRL+C to abort)"
			sleep $restart_loop_delay

		elif (( $UID )); then

			G_WHIP_MSG '[FAILED] Root login required\n
To finish DietPi first run setup, root permissions are required.\n
Please login again as user "root" with password "dietpi", respectively the one you chose via "dietpi.txt".'

			exit 1

		# Proceed with 1st run setup
		else

			# Prevent re-run from another session.
			echo $$ > $FP_DIETPI_FIRSTRUNSETUP_PID
			# - Always remove PID file when script is killed
			trap '[[ -f $FP_DIETPI_FIRSTRUNSETUP_PID ]] && rm $FP_DIETPI_FIRSTRUNSETUP_PID' EXIT

			Show_License

			# 1st run dietpi-update
			if (( $G_DIETPI_INSTALL_STAGE == 0 )); then

				# Checking network connectivity
				# shellcheck disable=SC2119
				G_CHECK_CON

				# Checking DNS resolver
				# shellcheck disable=SC2119
				G_CHECK_DNS

				# Network time sync
				/boot/dietpi/func/run_ntpd

				# Start DietPi-Update
				/boot/dietpi/dietpi-update 1 # Sets /boot/dietpi/.install_stage > G_DIETPI_INSTALL_STAGE=1

				# Prompt on failure
				(( $(</boot/dietpi/.install_stage) == 1 )) || Prompt_on_Failure

			# 1st run dietpi-software installs
			elif (( $G_DIETPI_INSTALL_STAGE == 1 )); then

				# Start DietPi-Software
				/boot/dietpi/dietpi-software 2>&1 | tee $FP_DIETPI_FIRSTRUNSETUP_LOG # Sets /boot/dietpi/.install_stage > G_DIETPI_INSTALL_STAGE=2

				# Prompt on failure
				(( $(</boot/dietpi/.install_stage) == 2 )) || Prompt_on_Failure

			fi

		fi

	}

	Main(){

		# Prevent automated nested dietpi-login calls from subshells
		export G_DIETPI_LOGIN=1

		while :
		do
			# Import DietPi-Globals --------------------------------------------------------------
			. /boot/dietpi/func/dietpi-globals
			G_PROGRAM_NAME='DietPi-Login'
			#G_INIT # To allow concurrent logins
			# Import DietPi-Globals --------------------------------------------------------------

			/boot/dietpi/func/obtain_network_details

			#----------------------------------------------------------------
			# Normal Login
			if (( $G_DIETPI_INSTALL_STAGE == 2 )); then

				/boot/dietpi/func/dietpi-banner 1

				# DietPi-AutoStart
				# - Skip if this is a desktop/X session already
				[[ $DISPLAY ]] && break
				# - Skip if autologin is not enabled
				[[ -f '/etc/systemd/system/getty@tty1.service.d/dietpi-autologin.conf' ]] || break
				# - Skip if this is not the main TTY1
				[[ $(readlink -f /proc/$$/fd/1) == '/dev/tty1' ]] || break
				# - Skip if there is no DietPi-AutoStart config
				[[ -f '/boot/dietpi/.dietpi-autostart_index' ]] || break

				Run_AutoStart "$(</boot/dietpi/.dietpi-autostart_index)"
				break

			#----------------------------------------------------------------
			# Run DietPi-Update/DietPi-Software (1st run setup) (G_DIETPI_INSTALL_STAGE=0/1)
			elif [[ $G_DIETPI_INSTALL_STAGE == [01] ]]; then

				/boot/dietpi/func/dietpi-banner 0
				Run_DietPi_First_Run_Setup

			#----------------------------------------------------------------
			# Unknown install state
			else

				Prompt_on_Failure

			fi
		done

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	Main

	#-----------------------------------------------------------------------------------
	exit
	#-----------------------------------------------------------------------------------
}
